<?php
namespace com\rs\dns\controller\api;

use com\rs\dns\constant\CommonConstant;
use com\rs\dns\controller\api\vo\RecordForm;
use com\rs\dns\controller\api\vo\RecordQuery;
use com\rs\dns\controller\api\vo\UrlForm;
use com\rs\dns\controller\BaseController;
use com\rs\dns\exception\BaException;
use com\rs\dns\service\DomainService;
use com\rs\dns\service\UrlService;
use restphp\http\RestHttpRequest;
use restphp\http\RestHttpStatus;


/**
 * Class UserUrlController.
 * @package com\rs\dns\controller\api
 * @RequestMapping("/api/user/urls")
 */
final class UserUrlController extends BaseController {
    /**
     * 域名管理列表.
     * @RequestMapping(value="", method="GET")
     */
    public function recordList() {
        $pageParam = RestHttpRequest::getPageParam();
        $recordQuery = RestHttpRequest::getParameterAsObject(new RecordQuery());
        $domainList = UrlService::getManageList($recordQuery, $pageParam, $this->_getUsername());
        $this->_success($domainList);
    }

    /**
     * 新增域名.
     * @RequestMapping(value="", method="POST")
     * @throws BaException
     */
    public function add() {
        $urlForm = RestHttpRequest::getRequestBody(new UrlForm(), true);
        if (!DomainService::hadDomain($urlForm->getOrigin(), $this->_getUsername())) {
            throw new BaException(CommonConstant::NO_RIGHT_TO_OPERATING_THE_DATA, RestHttpStatus::Forbidden);
        }
        UrlService::add($urlForm);
    }

    /**
     * 修改转发信息.
     * @RequestMapping(value="/{id}", method="PUT")
     * @throws BaException
     */
    public function modify() {
        $urlForm = RestHttpRequest::getRequestBody(new UrlForm(), true);
        $id = RestHttpRequest::getPathValue("id");
        if (!UrlService::hadUrl($id, $this->_getUsername())) {
            throw new BaException(CommonConstant::NO_RIGHT_TO_OPERATING_THE_DATA, RestHttpStatus::Forbidden);
        }
        UrlService::modify($id, $urlForm);
    }

    /**
     * 单个删除转发.
     * @RequestMapping(value="/{id}", method="DELETE")
     * @throws BaException
     */
    public function delete() {
        $id = RestHttpRequest::getPathValue("id");
        if (!UrlService::hadUrl($id, $this->_getUsername())) {
            throw new BaException(CommonConstant::NO_RIGHT_TO_OPERATING_THE_DATA, RestHttpStatus::Forbidden);
        }
        UrlService::delete($id);
    }

    /**
     * 批量删除域名.
     * @RequestMapping(value="/actions/delete", method="POST")
     * @throws BaException
     */
    public function deleteDomainBatch() {
        $arrId = RestHttpRequest::getRequestBody();
        if (null == $arrId || empty($arrId)) {
            throw new BaException(CommonConstant::DATA_TO_DELETE_CAN_NOT_NULL);
        }
        if (!UrlService::hadUrls($arrId, $this->_getUsername())) {
            throw new BaException(CommonConstant::NO_RIGHT_TO_OPERATING_THE_DATA, RestHttpStatus::Forbidden);
        }
        UrlService::batchDelete($arrId);
    }
}